package gameoflife.view;

import gameoflife.GameOfLife;

import java.awt.Color;
import java.awt.Container;

import javax.swing.JFrame;
import javax.swing.SwingUtilities;

public class SwingGameOfLife extends JFrame {

	private static final long serialVersionUID = 1L;
	private Container content;
	private GameOfLife game;
	private GameOfLifePanel gamePanel;

	public SwingGameOfLife() {
		game = new GameOfLife(500, 500);
		addGlider(0);
		addGlider(5);
		addGlider(20);
		content = getContentPane();
		content.setBackground(Color.WHITE);
		gamePanel = new GameOfLifePanel(game);
		content.add(gamePanel);
		setDefaultCloseOperation(EXIT_ON_CLOSE);
		setSize(400, 400);
	}

	public void startGame() {

		new Thread(new Runnable() {

			@Override
			public void run() {
				while (true) {
					game.tick();
					SwingUtilities.invokeLater(new Runnable() {

						@Override
						public void run() {
							gamePanel.repaint();
						}
					});
					try {
						Thread.sleep(100);
					} catch (InterruptedException e) {
						e.printStackTrace();
					}
				}
			}
		}).start();
	}

	private void addGlider(int offset) {
		game.setLive(0 + offset, 0 + offset);
		game.setLive(1 + offset, 1 + offset);
		game.setLive(2 + offset, 1 + offset);
		game.setLive(1 + offset, 2 + offset);
		game.setLive(2 + offset, 0 + offset);

	}

	public static void main(String[] args) {
		final SwingGameOfLife game = new SwingGameOfLife();
		SwingUtilities.invokeLater(new Runnable() {

			@Override
			public void run() {
				game.setVisible(true);
			}
		});
		game.startGame();
	}

}
